<?php

namespace App\Bizs\Mp1;

use App\Exceptions\BizException;
use App\Models\AreaModel;
use App\Models\MessageModel;
use App\Models\UserModel;
use App\Support\SmsSupport;
use App\Supports\DateSupport;
use Base\BaseBiz;
use Base\BaseException;
use GuzzleHttp\Client;
use Lib\Log;
use Lib\RedisManager;

class UserBiz extends BaseBiz
{
    /**
     * 用户登录
     * @param $params
     * @return array
     * @throws BizException
     * @throws BaseException
     */
    public function mpLogin($params)
    {
        if (empty($params['jscode'])) {
            throw new BizException('缺少微信认证code');
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='. config('env.MP_APPID') .'&secret='. config('env.MP_SECRET') .'&js_code='. $params['jscode'] .'&grant_type=authorization_code';

        $wxResJson = (new Client())->get($url)->getBody();
        $wxRes = json_decode($wxResJson, true);
        if (!$wxRes) {
            throw new BizException("微信登录失败。");
        }
        if (isset($wxRes['errcode']) && $wxRes['errcode'] != 0) {
            Log::error(json_encode($wxResJson));
            throw new BizException("微信登录失败。" . $wxRes['errmsg']);
        }
        $openid = $wxRes['openid'];

        $user = (new UserModel())->getUserByOpenid($openid, "*");
        if (empty($user)) {
            $user = [
                'openid' => $openid,
                'create_time' => DateSupport::nowDate()
            ];
            $uid = (new UserModel())->insertUser($user);
            $user['id'] = $uid;
//            $tempToken = md5($openid . rand(1000, 9999));
//            RedisManager::init()->setex(config('keys.redis.TEMP_TOKEN') . $tempToken, 86400, $openid);
//            return [
//                'data' => ['temp_token' => $tempToken],
//                'msg' => '请绑定手机号',
//                'code' => BizException::PLEASE_BIND_MOBILE
//            ];
        }
//        if (empty($user['mobile'])) {
//            $tempToken = md5($openid . rand(1000, 9999));
//            RedisManager::init()->setex(config('keys.redis.TEMP_TOKEN') . $tempToken, 86400, $openid);
//            return [
//                'data' => ['temp_token' => $tempToken],
//                'msg' => '请绑定手机号',
//                'code' => BizException::PLEASE_BIND_MOBILE
//            ];
//        }

        $token = md5(implode('|', [
            $user['id'],
            $openid,
            rand(1000, 9999)
        ]));
        RedisManager::init()->setex(config('keys.redis.USER_TOKEN') . $token, 8640000, base64_encode(json_encode($user)));
        unset($user['openid']);
        return [
            'data' => array_merge($user, [
                'token' => $token,
                'exp' => 8640000
            ]),
            'msg' => '',
            'code' => 200
        ];
    }

    public function sendVCode($params)
    {
        if (empty($params['mobile'])) {
            throw new BizException('请输入手机号');
        }
        if (empty($params['temp_token'])) {
            throw new BizException('请返回上一页重新授权登录', BizException::PLEASE_RE_WX_LOGIN);
        }
        $openid = RedisManager::init()->get(config('keys.redis.TEMP_TOKEN') . $params['temp_token']);
        if (!$openid) {
            throw new BizException('请返回上一页重新授权登录', BizException::PLEASE_RE_WX_LOGIN);
        }

        $vCode = rand(1000, 9999);
        RedisManager::init()->setex(config('keys.redis.SMS') . $params['mobile'], 3600, $vCode);
        $send = SmsSupport::sendMsg($params['mobile'], [$vCode]);
        if ($send) {
            return ['send' => $send];
        } else {
            throw new BizException('验证码发送失败');
        }
    }

    /**
     * 获取用户信息
     * @param $uid
     * @return array
     */
    public function getUserInfo($uid)
    {
        $userinfo = (new UserModel())->getUserByUid($uid, "*");
        if ($userinfo['city'] > 0) {
            $city = (new AreaModel())->getAreaById($userinfo['city']);
        }
        if ($userinfo['province'] > 0) {
            $province = (new AreaModel())->getAreaById($userinfo['province']);
        }
        $userinfo['city_name'] = $city ? $city['name'] : '';
        $userinfo['province_name'] = $province ? $province['name'] : '';

        return $userinfo;
    }

    /**
     * 保存用户信息
     * @param $params
     * @param $uid
     * @return array
     * @throws BizException
     */
    public function setUserInfo($params, $uid)
    {
        $user = (new UserModel())->getUserByUid($uid);
        $updateArr = [];
        if (isset($params['nickname']) && $user['nickname'] != $params['nickname']) {
            $updateArr['nickname'] = $params['nickname'] ?? '';
        }
        if (isset($params['icon']) && $user['icon'] != $params['icon']) {
            $updateArr['icon'] = $params['icon'] ?? '';
        }
        if (isset($params['sina']) && $user['sina'] != $params['sina']) {
            $updateArr['sina'] = $params['sina'] ?? '';
        }
        if (isset($params['gender']) && $user['gender'] != $params['gender']) {
            $updateArr['gender'] = $params['gender'] ?? '';
        }
        if (isset($params['city']) && $user['city'] != $params['city']) {
            $updateArr['city'] = $params['city'] ?? '';
        }
        if (isset($params['province']) && $user['province'] != $params['province']) {
            $updateArr['province'] = $params['province'] ?? '';
        }
        if (isset($params['mobile']) && $user['mobile'] != $params['mobile']) {
            $updateArr['mobile'] = $params['mobile'] ?? '';
        }
        if (isset($params['weixin']) && $user['weixin'] != $params['weixin']) {
            $updateArr['weixin'] = $params['weixin'] ?? '';
        }

        if (empty($updateArr)) {
            throw new BizException('没有修改任何内容');
        }

        $updateArr = array_merge($updateArr, [
            'modify_time' => DateSupport::nowDate()
        ]);
        try {
            $update = (new UserModel())->updateUserByUid($uid, $updateArr);
            return [
                'update' => $update
            ];
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            throw new BizException('保存用户信息时出现问题');
        }
    }

    public function getUnreadMessageCount($uid)
    {
        return (new MessageModel())->getMyUnreadCount($uid);
    }

    public function getUserDetail($uid)
    {
        return $this->getUserInfo($uid);
    }
}
